/**********
    @name: icon.js
    @describtion:
        写入线上图标库的cdn地址，通过遍历CSS样式表选择器获取图标类名来加载选择器以及建立图标组件
        getIconfontNames resolve:所有iconfont图标类名
    @author:liubingye
    @date:2023-01-17 16:25:37
***********/

/*
 * 加载网络css文件
 */
import { nextTick } from "vue";

// 静态配置文件中css cdn
const cssUrls = document.configs.cssUrls
/*
 * 加载预设的字体图标资源
 */
export default function init() {
    if (cssUrls.length > 0) {
        cssUrls.map((v) => {
            loadCss(v)
        })
    }
}

function loadCss(url) {
    const link = document.createElement('link')
    link.rel = 'stylesheet'
    link.href = url
    link.crossOrigin = 'anonymous'
    document.getElementsByTagName('head')[0].appendChild(link)
}

function getStylesFromDomain(domain) {
    const sheets = []
    const styles = document.styleSheets
    for (const key in styles) {
        if (styles[key].href && (styles[key].href).indexOf(domain) > -1) {
            sheets.push(styles[key])
        }
    }
    return sheets
}

/*
 * 获取 Iconfont 的 name 列表
 */
export function getIconfontNames() {
    return new Promise((resolve, reject) => {
        nextTick(() => {
            const iconfonts = []
            const sheets = getStylesFromDomain('at.alicdn.com')
            for (const key in sheets) {
                const rules = sheets[key].cssRules
                for (const k in rules) {
                    if (rules[k].selectorText && /^\.icon-(.*)::before$/g.test(rules[k].selectorText)) {
                        iconfonts.push(`${rules[k].selectorText.substring(1, rules[k].selectorText.length).replace(/::before/gi, '')}`)
                    }
                }
            }

            if (iconfonts.length > 0) {
                resolve(iconfonts)
            } else {
                reject('No Iconfont style sheet')
            }
        })
    })
}
